<template>
  <div class="adContainer">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>广告管理</span>
        <el-button @click="addAdBtn" style="float:right; margin:-8px;" type="success">添加广告图</el-button>
        <el-dialog
        title="提示"
        :visible.sync="addAddialog"
        width="30%"
        :before-close="addSwiperdialogClose">
        <!-- 轮播图上传 -->
        <el-upload
        class="upload-demo"
        ref="upload"
        action="http://localhost:3000/api/upload/adupload"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="uploadFinish"
        :limit="1"
        :file-list="fileList"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传一个jpg/png文件，且不超过500kb</div>
        </el-upload>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancelAddAd()">取 消</el-button>
            <el-button type="primary" @click="sureAddAd()">确 定</el-button>
        </span>
        </el-dialog>
      </div>
      <div class="adForm">
        <el-table
          :data="adData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
          style="width: 100%"
        >
          <el-table-column label="日期" prop="create_time"></el-table-column>
          <el-table-column label="图片ID" prop="id"></el-table-column>
          <el-table-column label="图片名" prop="img_name"></el-table-column>
          <el-table-column label="图片地址">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>图片名称: {{ scope.row.img_name }}</p>
                <p>图片地址: {{ scope.row.img_url }}</p>
                <div slot="reference" class="name-wrapper">
                  <img class="adImg" :src="scope.row.img_url" alt />
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="上传人" prop="author"></el-table-column>
          <el-table-column align="right">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"><a :href="scope.row.img_url" class="displayImg" target="_blank">查看大图</a></el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage1"
        :page-sizes="pageSizeArr"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getAdsApi, delAdApi,adUploadApi,sureAddAdApi } from "@/api/ad";
export default {
  data() {
    return {
      adData: [
        {
          create_time: "2016-05-02",
          author: "王小虎",
          img_url: "上海市普陀区金沙江路 1518 弄",
          img_name: "上海市普陀区金沙江路 1518 弄"
        }
      ],
      search: "",
      currentPage1: 1,
      total:0,
      pageSizeArr:[5,10,20,40,80],
      pageSize:'',
      addAddialog:false,
      delFileName:'',
      filename:'',
      fileList:[]
    };
  },
  methods: {
    // 封装获取广告
    async getAds(data) {
      if (data) {
        await getAdsApi(data).then(res => {
          if (res.data.code == 1000) {
            this.adData = res.data.ads;
            this.total = res.data.total;
          }
        });
      } else {
        const data = { pageSize: "", pageNum: "" };
        await getAdsApi(data).then(res => {
          if (res.data.code == 1000) {
            this.adData = res.data.ads;
            this.total = res.data.total;
          }
        });
      }
    },
    // 封装删除图片上传和数据库图片
    async delAd(data){
        await delAdApi(data)
    },
    // 查看大图
    handleEdit(index, row) {
      console.log(index, row);
    },
    // 删除广告
    async handleDelete(index, row) {
        this.$confirm(`此操作将永久删除该文件${row.img_name}, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
            const data = {filename:row.img_name,adId:row.id}
            await this.delAd(data).then(async res=>{
                const data ={pageSize:this.pageSize,pageNum:this.currentPage1}
                await this.getAds(data)
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 每页数据变化
    async handleSizeChange(val) {
        this.pageSize = val
        const data ={pageSize:this.pageSize,pageNum:this.currentPage1}
        await this.getAds(data)
    },
    // 页码变化
    async handleCurrentChange(val) {
        this.currentPage1 = val
        const data ={pageSize:this.pageSize,pageNum:this.currentPage1}
        await this.getAds(data)
    },
    // 添加广告按钮
    addAdBtn(){
        this.addAddialog = true
    },
    //   取消添加轮播图
    async cancelAddAd(){
        this.addSwiperdialog = false
        this.$message({
            type:'success',
            message:'取消添加成功'
        })
        if(this.delFileName){
                const data = {filename:this.delFileName}
                await delAdApi(data).then(async res=>{
                    this.delFileName = ''
                    this.fileList = []
                    this.addSwiperdialog = false
                }).catch(err=>{

                })
            }
      },
    //   上传完成
    uploadFinish(res,file){
        console.log(res);
        this.imageUrl = res.fileUrl
        this.delFileName = res.filename
        this.fileName = res.filename
        this.$message({
            type:'success',
            message:'上传成功'
        })
      },
    // 对话框关闭
    addSwiperdialogClose(done) {
        this.$confirm('确认关闭？')
          .then(async _  => {
            if(this.delFileName){
                const data = {filename:this.delFileName}
                await delAdApi(data).then(async res=>{
                    this.delFileName = ''
                    this.fileList = []
                }).catch(err=>{

                })
            }else{
            this.addSwiperdialog = false
            this.$message({
                type:'success',
                message:'取消添加成功'
            })
            }
            done();
          })
          .catch(_ => {});
      },
    //   确认上传
    async sureAddAd(){
        if(this.delFileName){
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        const data = {img_url:this.imageUrl,img_name:this.fileName,author:userInfo.username}
        await sureAddAdApi(data).then(async res=>{
            this.delFileName = ''
            this.fileList = []
            this.addAddialog = false
            await this.getAds();
        })
        }else{
            this.$message({
                type:'error',
                message:'请先上传图片'
            })
        }
    },
    submitUpload() {
        this.$refs.upload.submit();
      },
    handleRemove(file, fileList) {
        console.log(file, fileList);
      },
    handlePreview(file) {
        console.log(file);
      }
  },
  async mounted() {
    await this.getAds();
  }
};
</script>

<style lang="less" scoped>
.adContainer {
  height: 80vh;
  .adForm {
    height: 70vh;
    overflow: auto;
  }
  .adImg {
    width: 120px;
    height: 80px;
  }
  .displayImg {
    text-decoration: none;
    color: #909399;
  }
}
</style>
